package com.dk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dk.mapper.PersonRoleMapper;
import com.dk.mapper.TPersonMapper;
import com.dk.pojo.PersonRole;
import com.dk.pojo.PersonRoleExample;
import com.dk.pojo.TPerson;
import com.dk.pojo.TPersonExample;
import com.dk.service.TPersonServiceI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Component
public class TPersonServiceImpl implements TPersonServiceI {

    //用户表
    @Autowired
    private TPersonMapper tPersonMapper;

    //角色用户中间表
    @Autowired
    private PersonRoleMapper personRoleMapper;

    @Override
    public List<TPerson> getAll() {
        List<TPerson> list = tPersonMapper.selectByExample(new TPersonExample());
        return list;
    }


    //事物管理(注解)
    @Transactional
    @Override
    public void addById(TPerson tPerson, Integer[] roleIds) {
        //增加并返回ID
        int i = tPersonMapper.addById(tPerson);

        //增加用户角色表
        List<PersonRole> personRoles = new ArrayList<>();
        for (Integer roleId : roleIds){
            PersonRole personRole = new PersonRole();
            personRole.setPersonId(tPerson.getPid());
            personRole.setRoleId(roleId);
            personRoles.add(personRole);
        }
        int j = personRoleMapper.insertBatch(personRoles);
    }

    @Override
    public TPerson getUpdate(Integer pid) {
        return tPersonMapper.selectByPrimaryKey(pid);
    }

    //事物管理(注解)
    @Transactional
    @Override
    public void updateById(TPerson tPerson, Integer[] roleIds) {

        tPersonMapper.updateByPrimaryKeySelective(tPerson);
        PersonRoleExample example = new PersonRoleExample();
        PersonRoleExample.Criteria criteria = example.createCriteria();
        criteria.andPersonIdEqualTo(tPerson.getPid());
        personRoleMapper.deleteByExample(example);

        //增加用户角色表
        List<PersonRole> personRoles = new ArrayList<>();
        for(Integer roleId : roleIds){
            PersonRole personRole = new PersonRole();
            personRole.setPersonId(tPerson.getPid());
            personRole.setRoleId(roleId);
            personRoles.add(personRole);
        }
        int j = personRoleMapper.insertBatch(personRoles);
    }

    @Override
    public void deleteInfo(Integer pid) {

        tPersonMapper.deleteByPrimaryKey(pid);

        PersonRoleExample example = new PersonRoleExample();
        PersonRoleExample.Criteria criteria = example.createCriteria();
        criteria.andPersonIdEqualTo(pid);
        personRoleMapper.deleteByExample(example);
    }
}
